/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is moodmill.
 *
 * The Initial Developer of the Original Code is
 * Akhmad Fathonih.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

if (!moodmill) // ifdef ;), include_once
{
var moodmill = (function() {
   this.arrMood = new Array('bad mood', 'low spirit', 'hmm', 'high spirit', 'excited');
   this.curMood = 3;
   this.retries = 0;
   this.authObj = null;
  this.onLoad = function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("moodmill-strings");
    
    //if (this.getAuthObject()==null)
    this.upgrade();
    
    this.authObj = this.getAuthObject();

    this.getCurMood();
    this.loggedIn = false;
    
    var oldUserName = Preference.getString('extensions.moodmill.username', null);
    if (this.getUser()!=null) {
      // isntalled, need update
      this.login(this.getUser(), this.getPass(), false);
    } else {
     // nto isntalled
      this.showPrefs();
    }
  }
  
  this.getUser = function() {
      //return Preference.getString('extensions.moodmill.username', null);
      return this.authObj.user;
  }
  
  this.getPass = function() {
      //return Preference.getString('extensions.moodmill.password', null);
      return this.authObj.password;
  }
  
  this.onMenuItemCommand = function(e) {
    var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                  .getService(Components.interfaces.nsIPromptService);
    promptService.alert(window, this.strings.getString("helloMessageTitle"),
                                this.strings.getString("helloMessage"));
  }
  
  this.updateMoodBar = function(e) {
    var idx = /moodmill-moodbar-(\d)/.exec(e.target.id);
    if (idx)
      this.showMood(idx[1]);
  }
  
  this.showMoodbar = function(pos) {
      var moodbar = document.getElementById('moodmill-moodbar-' + pos);
      moodbar.style.backgroundPosition= '-' + (pos-1)*30 + 'px' + ' -30px';
  }
  
  this.hideMoodbar = function(pos) {
      var moodbar = document.getElementById('moodmill-moodbar-' + pos);
      moodbar.style.backgroundPosition= '-' + (pos-1)*30 + 'px' + ' 0px';
  }
  
  this.mouseleave = function(e) {
//     var moodbar = document.getElementById('moodmill-moodbar');
//     moodbar.style.height= '15px';
  }
  
  this.action = function(e) {
      var idx = /moodmill-moodbar-(\d)/.exec(e.target.id);
      var mood_rate = idx[1];

      var features = "resizeable=yes,titlebar,toolbar,centerscreen,modal,height=250,width=500";
      var url = "chrome://moodmill/content/mooddlg.xul";
      var params = {'input':{'rate': mood_rate}, 'output':null};
      window.openDialog(url, "moodmill", features, params).focus();
      if (params.output != null) {
         this.postMood(params.output.rate, params.output.desc, params.output.url);
      } else {
         Logger.log('no mood submission');
      }
  }
  
  this.postMood = function(mood_rate, mood_desc, mood_url) {
      Logger.log("Posting your mood\nMood Rate: "+mood_rate+"\nMood Desc: "+mood_desc+"\nMood URL: " + mood_url);
      this.cacheMood(mood_rate, mood_desc, mood_url);

      var url = 'http://www.moodmill.com/ajax.php';
      var postdata = 'act=mood_submit&mood-rate=' + mood_rate + '&mood-desc=' + escape(mood_desc) + '&mood-url=' + escape(mood_url);
      this.showProgress();
      YAHOO.util.Connect.asyncRequest('POST', url , {success: this.handleSuccess ,failure:function(o){alert('Error: ' + o.statusText + "\n" + o.responseText)}, argument: {'mood': mood_rate}, scope: this}, postdata);
  }
  
  this.handleSuccess = function(o) {
      //alert(o.responseText);
      this.stopProgress();
      if (/Sorry,/.test(o.responseText)) {
         //alert('Sorry, you need to login first (manually) to moodmill.com');
         this.retry();
      } else {
         alert("Yipeee\n" + o.responseText);
         this.cacheAvailable = false; // invalidate mood cache
         this.curMood = this.cacheMoodRate;
         this.showCurMood();
      }
  }
  
  this.getCurMood = function() {
      Logger.log('getCurMood for user: ' + this.getUser());
      var url = 'http://www.moodmill.com/rss/' + this.getUser() + '/?' + Math.random();
      this.showProgress();
      YAHOO.util.Connect.asyncRequest('GET', url , {success: this.handleCurMood ,failure:function(o){this.stopProgress(); alert('Error retrieving current mood: ' + o.statusText + "\n" + o.responseText)}, scope: this});
  }
  
  this.handleCurMood = function(o) {
      //Logger.log('Reponse mood: ' + o.responseText);
      var cur_mood = /<title>.*?\[(.*?)\].*?<\/title>/.exec(o.responseText);
      Logger.log('Current mood: ' + cur_mood);
      var mood_rate = 3;
      //Logger.log(this.arrMood.length);
      var len = this.arrMood.length;
      for(var i=0;i<len;i++) {
         var re = new RegExp(this.arrMood[i], 'i');
         Logger.log("testing: " + this.arrMood[i] + " in " + cur_mood[1]);
         if (re.test(cur_mood[1])) {
            mood_rate = i+1;
            break;
         }
      }
      Logger.log('Got mood_rate: ' + mood_rate);
      this.curMood = mood_rate;
      this.showMood(mood_rate);
      this.stopProgress();
  }
  
  this.cacheMood = function(rate, desc, url) {
      this.cacheAvailable = true;
      this.cacheMoodRate = rate;
      this.cacheMoodDesc = desc;
      this.cacheMoodUrl = url;
  }
  
  this.login = function(user, pass, callback) {
      Logger.log('Logging you in, hold tight ...');
      //f_id=neofreko&f_password=xxx&f_submit.x=33&f_submit.y=8&f_submit=Submit
      //http://www.moodmill.com/login/next//
      var url = 'http://www.moodmill.com/login/next//';
      var postdata = 'f_id=' + user + '&f_password=' + pass + '&f_submit.x=33&f_submit.y=8&f_submit=Submit';
      this.showProgress();
      YAHOO.util.Connect.asyncRequest('POST', url , {success: function(o) {this.stopProgress();this.loggedIn = true; if (callback) callback(); Logger.log('Logged in ^^. Yattaaa ...');} ,failure:function(o){this.stopProgress();alert('Error: ' + o.statusText + "\n" + "\nUnable to login using current user/pass\n" + o.responseText)}, scope: this}, postdata);
  }
  
  this.retry = function() {
      if (this.retries > 10) {
         Logger.log('Reached maximum retries! Stopping.');
         this.retries = 0;
         return;
      }
      Logger.log('Retry #' + this.retries);
      this.login(this.getUser(), this.getPass(), function() {this.postMood(this.cacheMoodRate, this.cacheMoodDesc, this.cacheMoodUrl);});
  }
  
  this.showMood = function(mood) {
      //Logger.log('ShowMood: ' + mood);
      for(var i=1;i<=5;i++) {
         if (i>mood)
            this.hideMoodbar(i);
         else
            this.showMoodbar(i);
      }
  }
  
  this.showCurMood = function() {
      Logger.log('ShowCurMood: ' + this.curMood);
      this.showMood(this.curMood);
  }
  
  this.showProgress = function() {
      var progress = document.getElementById('moodmill-config-image');
      progress.src = 'chrome://moodmill/skin/ajax-loading-small.gif';
  }
  
  this.stopProgress = function() {
      var progress = document.getElementById('moodmill-config-image');
      progress.src = 'chrome://moodmill/skin/statusbar.png';
  }
  
  this.showPrefs = function() {
      var features = "resizeable=yes,titlebar,toolbar,centerscreen,modal,height=200,width=300";
      var url = "chrome://moodmill/content/options.xul";
      window.openDialog(url, "moodmill_pref", features).focus();
  }
  
  this.showAbout = function() {
      var features = "resizeable=yes,titlebar,toolbar,centerscreen,modal";
      var url = "chrome://moodmill/content/about-moodmill.xul";
      window.openDialog(url, "moodmill_about", features).focus();
  }
  
  this.getAuthObject = function() {
    var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"].getService(Components.interfaces.nsIPasswordManager);
    // the host name of the password we are looking for
    var queryString = 'http://www.moodmill.com';
    // ask the password manager for an enumerator:
    var e = passwordManager.enumerator;
    // step through each password in the password manager until we find the one we want:
    while (e.hasMoreElements()) {
        try {
            // get an nsIPassword object out of the password manager.
            // This contains the actual password...
            var pass = e.getNext().QueryInterface(Components.interfaces.nsIPassword);
            if (pass.host == queryString) {
                // found it!]
                return pass;
//                 alert(pass.user); // the username
//                 alert(pass.password); // the password
                break;
            }
        } catch (ex) {
            // do something if decrypting the password failed--probably a continue
            return null;
        }
    }
  }
  
  this.upgrade = function() {
    // update to new security method
    var username = Preference.getString('extensions.moodmill.username', null);
    var userpass = Preference.getString('extensions.moodmill.password', null);
    
    if ((username =='already-upgraded-to-new-version') && (userpass =='already-upgraded-to-new-version')) {
        Logger.log("No upgrade needed");
        return;
    } else {
        Logger.log("Upgrading to new version");
        var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"].getService(Components.interfaces.nsIPasswordManager);
        passwordManager.addUser('http://www.moodmill.com', username, userpass);
    }
    
    Preference.setString('extensions.moodmill.username', 'already-upgraded-to-new-version');
    Preference.setString('extensions.moodmill.password', 'already-upgraded-to-new-version');
  }
})();
window.addEventListener("load", function(e) { moodmill.onLoad(e); }, false);
}
